package main

import (
	"context"
	"fmt"
	zipkin "github.com/go-kit/kit/tracing/zipkin"
	kit_grpc "github.com/go-kit/kit/transport/grpc"
	http1 "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	openzipkip "github.com/openzipkin/zipkin-go"
	"github.com/openzipkin/zipkin-go/reporter/http"
	Endpoint2 "go-kit/demo6/Endpoint"
	"go-kit/demo6/Services"
	Transport2 "go-kit/demo6/Transport"
	pd2 "go-kit/go-client/pd"
	"google.golang.org/grpc"
	netHttp "net/http"
	"os"
	"reflect"
)

//挂起一个HTTP 服务 并把请求 传递给service 层
func main() {

	user := Services.UserService{}
	endp := Endpoint2.GetUserEndPoint(user)

	serverHandler := http1.NewServer(endp, Transport2.DecodeUserTransport, Transport2.EncodeUserTransport)

	r := mux.NewRouter()

	//所有方式都能访问
	//r.Handle(`/user`, serverHandler)

	//GET 方式访问
	r.Methods("GET").Path(`/user/{uid:\d+}`).Handler(serverHandler)
	r.Methods("GET").Path(`/health`).HandlerFunc(func(writer netHttp.ResponseWriter, request *netHttp.Request) {

		cnon, err := grpc.Dial(":8080", grpc.WithInsecure())

		if err != nil {
			os.Exit(1)
		}

		//追踪器设置
		repoter := http.NewReporter("http://127.0.0.1:9411/api/v2/spans")

		//执行完成关闭
		defer repoter.Close()

		//新建追踪器
		zkTracet, _ := openzipkip.NewTracer(repoter)

		//启动追踪器客户端
		zkClientTrace := zipkin.GRPCClientTrace(zkTracet)

		bookInfoRequest := kit_grpc.NewClient(
			cnon,
			"GetUserInfo",
			"UserList",
			func(_ context.Context, in interface{}) (interface{}, error) { return nil, nil },
			func(_ context.Context, out interface{}) (interface{}, error) { return out, nil },
			pd2.Response{},
			zkClientTrace,
		).Endpoint()

		parentSpan := zkTracet.StartSpan("天王盖胖虎")

		ctx := openzipkip.NewContext(context.Background(), parentSpan)

		bookInfoRequest(ctx, request)

		prodClient := pd2.NewGetUserInfoClient(cnon)

		res, err := prodClient.UserList(context.Background(), &pd2.Request{UserId: 24})

		fmt.Println(reflect.TypeOf(res))
		fmt.Println(res.ResultList)

		//
		writer.Header().Set("Content-type", "application/json")
		//writer.Write([]byte(res.ResultList))

		defer parentSpan.Flush()

		defer cnon.Close()

	})

	//调用注册服务
	//utils.RegService()

	netHttp.ListenAndServe(`:8081`, r)

}
